package com.strongbj.iot.devices.amazondb.response.handle;

import java.util.Date;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.amazondb.entity.Tag;
import com.strongbj.iot.devices.amazondb.service.MongoDBService;
import com.strongbj.iot.devices.amazonreader.message.ReaderMessage;
import com.strongbj.iot.devices.amazonreader.request.message.MQMessage;
import com.strongbj.iot.devices.amazonreader.response.entity.CallLabelEntity;
import com.strongbj.iot.devices.amazonreader.response.entity.CallLabelFactory;
import com.strongbj.iot.devices.amazonreader.response.entity.DataCenterCallLabelReturnEntity;
import com.strongbj.iot.devices.amazonreader.response.entity.ExecutionState;
import com.strongbj.iot.devices.amazonreader.response.entity.IEntityFactory;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

/**
 * 数据中心呼叫标签的应答处理
 * 
 * @author yuzhantao
 *
 */
class DataCenterCallLabelResponseHandle implements IMessageHandle<ReaderMessage, Object> {
	private final static String MQ_TOPIC = "daio";
	private final static String ACTION_CODE = "collect010";
	private IEntityFactory<List<CallLabelEntity>> labelFactory = new CallLabelFactory();
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private static Logger logger = LogManager.getLogger(ActivelyUploadedLabelInfoResponseHandle.class.getName());
	private MongoDBService mongoDBSercice = (MongoDBService) ContextUtils.getBean("mongoDBService");
	@Override
	public boolean isHandle(ReaderMessage t) {
		if (t.getType() == 10) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, ReaderMessage t) {
		byte[] datas = t.getBody(); // 获取从Reader接收到的数据段信息
		logger.info("收到Reader主动上传的标签信息数据：" + ByteUtil.byteArrToHexString(datas, true));
		List<CallLabelEntity> labs = labelFactory.parse(datas); // 通过简单工厂模式将byte数组转为对象

		if (labs.size() == 0)
			return null;

		// 保存数据更新时间
		for (CallLabelEntity callLabelEntity : labs) {
			if(callLabelEntity.getCallState()==ExecutionState.Success) {
				Tag tag = mongoDBSercice.findById(callLabelEntity.getLabelId());
				if(tag==null) {
					tag = new Tag();
				}
				tag.setId(callLabelEntity.getLabelId());
				tag.setUpdateTime(new Date());
				mongoDBSercice.save(tag);
			}
		}

		// TODO 将对象发送到MQ还未完成
		MQMessage<DataCenterCallLabelReturnEntity> msg = this
				.baseLabel2MQMessage(ByteUtil.byteArrToHexString(t.getAddress()), labs);// 将Reader对象信息转为MQ格式的信息

		String json = JSON.toJSONString(msg); // 转为Json字符串
		topicSender.send(MQ_TOPIC, json); // 发送标签信息到MQ
		logger.info("向mq服务器[topic:" + MQ_TOPIC + "] json=" + json);
		return null;
	}

	private MQMessage<DataCenterCallLabelReturnEntity> baseLabel2MQMessage(String address, List<CallLabelEntity> labs) {
		MQMessage<DataCenterCallLabelReturnEntity> msg = new MQMessage<DataCenterCallLabelReturnEntity>();
		msg.setActionCode(ACTION_CODE);

		DataCenterCallLabelReturnEntity dccr = new DataCenterCallLabelReturnEntity();
		dccr.setDevAddrCode(address);
		dccr.setLabs(labs);
		msg.setAwsPostdata(dccr);
		return msg;
	}
}
